import MainLayout from '../components/layout/MainLayout'
import React, { useState, useEffect } from 'react';
import { Table, Card, Button, Space, Tag, Modal, Form, Input, Select, message, Row, Col, Statistic } from 'antd';
import { PlusOutlined, CarOutlined, LogoutOutlined } from '@ant-design/icons';
// import Layout from '../../components/Layout';

const { Option } = Select;

interface ParkingSpot {
  id: string;
  spotNumber: string;
  zone: string;
  floor: number;
  status: string;
  coordinates: { x: number; y: number };
  hourlyRate: number;
  isVIP: boolean;
  vehicleInfo?: {
    plateNumber: string;
    vehicleType: string;
    ownerName: string;
    checkInTime: string;
  };
}

interface ParkingStats {
  total: number;
  available: number;
  occupied: number;
  reserved: number;
  maintenance: number;
}

const Parking: React.FC = () => {
  const [parkingSpots, setParkingSpots] = useState<ParkingSpot[]>([
    {
      id: '1',
      spotNumber: 'A001',
      zone: 'A区',
      floor: 1,
      status: 'occupied',
      coordinates: { x: 100, y: 100 },
      hourlyRate: 5,
      isVIP: false,
      vehicleInfo: {
        plateNumber: '京A12345',
        vehicleType: 'car',
        ownerName: '张三',
        checkInTime: '2024-01-15T09:30:00Z'
      }
    },
    {
      id: '2',
      spotNumber: 'A002',
      zone: 'A区',
      floor: 1,
      status: 'available',
      coordinates: { x: 120, y: 100 },
      hourlyRate: 5,
      isVIP: false
    },
    {
      id: '3',
      spotNumber: 'B001',
      zone: 'B区',
      floor: 2,
      status: 'reserved',
      coordinates: { x: 100, y: 200 },
      hourlyRate: 8,
      isVIP: true
    },
    {
      id: '4',
      spotNumber: 'A003',
      zone: 'A区',
      floor: 1,
      status: 'available',
      coordinates: { x: 140, y: 100 },
      hourlyRate: 5,
      isVIP: false
    },
    {
      id: '5',
      spotNumber: 'C001',
      zone: 'C区',
      floor: 3,
      status: 'maintenance',
      coordinates: { x: 100, y: 300 },
      hourlyRate: 6,
      isVIP: false
    }
  ]);
  
  const [stats, setStats] = useState<ParkingStats>({
    total: 100,
    available: 65,
    occupied: 30,
    reserved: 3,
    maintenance: 2
  });
  
  const [loading, setLoading] = useState(false);
  const [checkInModalVisible, setCheckInModalVisible] = useState(false);
  const [checkOutModalVisible, setCheckOutModalVisible] = useState(false);
  const [checkInForm] = Form.useForm();
  const [checkOutForm] = Form.useForm();

  useEffect(() => {
    fetchParkingData();
    fetchStats();
  }, []);

  const fetchParkingData = async () => {
    setLoading(true);
    try {
      // 模拟API调用延迟
      await new Promise(resolve => setTimeout(resolve, 800));
      
      // 模拟从后端获取最新数据
      // const response = await api.get('/parking/spots');
      // setParkingSpots(response.data);
      
      // 使用当前状态计算统计数据
      setParkingSpots(prev => {
        const currentStats = calculateStats(prev);
        setStats(currentStats);
        return prev;
      });
      
      message.success('停车位数据已更新');
    } catch (error) {
      message.error('获取停车位数据失败');
    } finally {
      setLoading(false);
    }
  };

  const fetchStats = async () => {
    try {
      await new Promise(resolve => setTimeout(resolve, 500));
      // 计算实时统计数据
      const currentStats = calculateStats(parkingSpots);
      setStats(currentStats);
    } catch (error) {
      message.error('获取统计数据失败');
    }
  };

  const calculateStats = (spots: ParkingSpot[]): ParkingStats => {
    const total = spots.length;
    const available = spots.filter(s => s.status === 'available').length;
    const occupied = spots.filter(s => s.status === 'occupied').length;
    const reserved = spots.filter(s => s.status === 'reserved').length;
    const maintenance = spots.filter(s => s.status === 'maintenance').length;
    
    return { total, available, occupied, reserved, maintenance };
  };

  const handleCheckIn = async (values: any) => {
    try {
      setLoading(true);
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      const vehicleInfo = {
        plateNumber: values.plateNumber,
        vehicleType: values.vehicleType,
        ownerName: values.ownerName,
        checkInTime: new Date().toISOString()
      };

      setParkingSpots(prev => prev.map(spot => 
        spot.id === values.spotId 
          ? { ...spot, status: 'occupied', vehicleInfo }
          : spot
      ));

      // 更新统计数据
      const updatedSpots = parkingSpots.map(spot => 
        spot.id === values.spotId 
          ? { ...spot, status: 'occupied', vehicleInfo }
          : spot
      );
      setStats(calculateStats(updatedSpots));

      message.success('车辆入场成功');
      setCheckInModalVisible(false);
      checkInForm.resetFields();
    } catch (error) {
      message.error('车辆入场失败');
    } finally {
      setLoading(false);
    }
  };

  const handleCheckOut = async (values: any) => {
    try {
      setLoading(true);
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      const spot = parkingSpots.find(s => s.vehicleInfo?.plateNumber === values.plateNumber);
      if (!spot || !spot.vehicleInfo) {
        message.error('未找到该车辆信息');
        return;
      }

      // 计算停车费用
      const checkInTime = new Date(spot.vehicleInfo.checkInTime);
      const checkOutTime = new Date();
      const hours = Math.ceil((checkOutTime.getTime() - checkInTime.getTime()) / (1000 * 60 * 60));
      const fee = hours * spot.hourlyRate;
      
      setParkingSpots(prev => {
        const updatedSpots = prev.map(s => 
          s.vehicleInfo?.plateNumber === values.plateNumber
            ? { ...s, status: 'available', vehicleInfo: undefined }
            : s
        );
        
        // 使用更新后的数据计算统计
        setStats(calculateStats(updatedSpots));
        return updatedSpots;
      });

      message.success(`车辆出场成功！停车时长：${hours}小时，费用：¥${fee}`);
      setCheckOutModalVisible(false);
      checkOutForm.resetFields();
    } catch (error) {
      message.error('车辆出场失败');
    } finally {
      setLoading(false);
    }
  };

  const columns = [
    {
      title: '车位号',
      dataIndex: 'spotNumber',
      key: 'spotNumber',
      sorter: (a: ParkingSpot, b: ParkingSpot) => a.spotNumber.localeCompare(b.spotNumber),
    },
    {
      title: '区域',
      dataIndex: 'zone',
      key: 'zone',
      filters: [
        { text: 'A区', value: 'A区' },
        { text: 'B区', value: 'B区' },
        { text: 'C区', value: 'C区' },
      ],
      onFilter: (value: any, record: ParkingSpot) => record.zone === value,
    },
    {
      title: '楼层',
      dataIndex: 'floor',
      key: 'floor',
      sorter: (a: ParkingSpot, b: ParkingSpot) => a.floor - b.floor,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      filters: [
        { text: '空闲', value: 'available' },
        { text: '占用', value: 'occupied' },
        { text: '预约', value: 'reserved' },
        { text: '维护', value: 'maintenance' },
      ],
      onFilter: (value: any, record: ParkingSpot) => record.status === value,
      render: (status: string) => {
        const statusMap: Record<string, { color: string; text: string }> = {
          available: { color: 'green', text: '空闲' },
          occupied: { color: 'red', text: '占用' },
          reserved: { color: 'orange', text: '预约' },
          maintenance: { color: 'gray', text: '维护' }
        };
        const statusInfo = statusMap[status] || { color: 'default', text: status };
        return <Tag color={statusInfo.color}>{statusInfo.text}</Tag>;
      }
    },
    {
      title: '车牌号',
      key: 'plateNumber',
      render: (_: any, record: ParkingSpot) => {
        return record.vehicleInfo?.plateNumber || '-';
      }
    },
    {
      title: '车主',
      key: 'ownerName',
      render: (_: any, record: ParkingSpot) => {
        return record.vehicleInfo?.ownerName || '-';
      }
    },
    {
      title: '入场时间',
      key: 'checkInTime',
      render: (_: any, record: ParkingSpot) => {
        return record.vehicleInfo?.checkInTime ? 
          new Date(record.vehicleInfo.checkInTime).toLocaleString('zh-CN') : '-';
      }
    },
    {
      title: '小时费率',
      dataIndex: 'hourlyRate',
      key: 'hourlyRate',
      render: (rate: number) => `¥${rate}/小时`
    },
    {
      title: 'VIP',
      dataIndex: 'isVIP',
      key: 'isVIP',
      render: (isVIP: boolean) => isVIP ? <Tag color="gold">VIP</Tag> : '-'
    },
  ];

  const availableSpots = parkingSpots.filter(spot => spot.status === 'available');
  const occupiedVehicles = parkingSpots.filter(spot => spot.status === 'occupied' && spot.vehicleInfo);

  return (
    <MainLayout>
      <div style={{ padding: '24px' }}>
        <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
          <Col span={6}>
            <Card>
              <Statistic title="总车位" value={stats.total} />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic title="空闲车位" value={stats.available} valueStyle={{ color: '#3f8600' }} />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic title="占用车位" value={stats.occupied} valueStyle={{ color: '#cf1322' }} />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic title="预约车位" value={stats.reserved} valueStyle={{ color: '#fa8c16' }} />
            </Card>
          </Col>
        </Row>

        <Card 
          title="停车管理" 
          extra={
            <Space>
              <Button 
                type="primary" 
                icon={<CarOutlined />} 
                onClick={() => setCheckInModalVisible(true)}
                disabled={availableSpots.length === 0}
              >
                车辆入场
              </Button>
              <Button 
                icon={<LogoutOutlined />} 
                onClick={() => setCheckOutModalVisible(true)}
                disabled={occupiedVehicles.length === 0}
              >
                车辆出场
              </Button>
              <Button onClick={fetchParkingData} loading={loading}>
                刷新数据
              </Button>
            </Space>
          }
        >
          <Table
            columns={columns}
            dataSource={parkingSpots}
            rowKey="id"
            loading={loading}
            pagination={{
              pageSize: 10,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 条记录`
            }}
          />
        </Card>

        {/* 车辆入场模态框 */}
        <Modal
          title="车辆入场"
          open={checkInModalVisible}
          onCancel={() => {
            setCheckInModalVisible(false);
            checkInForm.resetFields();
          }}
          onOk={() => checkInForm.submit()}
          confirmLoading={loading}
          destroyOnClose
        >
          <Form form={checkInForm} onFinish={handleCheckIn} layout="vertical">
            <Form.Item
              name="plateNumber"
              label="车牌号"
              rules={[
                { required: true, message: '请输入车牌号' },
                { pattern: /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/, message: '请输入正确的车牌号格式' }
              ]}
            >
              <Input placeholder="如：京A12345" />
            </Form.Item>
            <Form.Item
              name="vehicleType"
              label="车辆类型"
              rules={[{ required: true, message: '请选择车辆类型' }]}
            >
              <Select placeholder="请选择车辆类型">
                <Option value="car">小轿车</Option>
                <Option value="truck">货车</Option>
                <Option value="motorcycle">摩托车</Option>
                <Option value="suv">SUV</Option>
              </Select>
            </Form.Item>
            <Form.Item
              name="ownerName"
              label="车主姓名"
              rules={[{ required: true, message: '请输入车主姓名' }]}
            >
              <Input placeholder="请输入车主姓名" />
            </Form.Item>
            <Form.Item
              name="spotId"
              label="停车位"
              rules={[{ required: true, message: '请选择停车位' }]}
            >
              <Select placeholder="请选择停车位">
                {availableSpots.map(spot => (
                  <Option key={spot.id} value={spot.id}>
                    {spot.spotNumber} - {spot.zone} ({spot.floor}楼) - ¥{spot.hourlyRate}/小时
                    {spot.isVIP && ' [VIP]'}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Form>
        </Modal>

        {/* 车辆出场模态框 */}
        <Modal
          title="车辆出场"
          open={checkOutModalVisible}
          onCancel={() => {
            setCheckOutModalVisible(false);
            checkOutForm.resetFields();
          }}
          onOk={() => checkOutForm.submit()}
          confirmLoading={loading}
          destroyOnClose
        >
          <Form form={checkOutForm} onFinish={handleCheckOut} layout="vertical">
            <Form.Item
              name="plateNumber"
              label="车牌号"
              rules={[{ required: true, message: '请选择车牌号' }]}
            >
              <Select placeholder="请选择要出场的车辆">
                {occupiedVehicles.map(spot => (
                  <Option key={spot.id} value={spot.vehicleInfo!.plateNumber}>
                    {spot.vehicleInfo!.plateNumber} - {spot.spotNumber} ({spot.vehicleInfo!.ownerName})
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Form>
        </Modal>
      </div>
    </MainLayout>
  );
};

export default Parking;




